#include "Application.h"
#include "../Utility/GameTimer.h"

#include <crtdbg.h>

INT WINAPI GameCode( HINSTANCE hInstance, HINSTANCE hprevInstance, LPWSTR lpCmdLine, int nCmdShow )
{
	// Set up checks for memory leaks.
	// Game Coding Complete reference - Chapter 21, page 834
	//
	int tmpDbgFlag = _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG );

	// set this flag to keep memory blocks around
	tmpDbgFlag |= _CRTDBG_DELAY_FREE_MEM_DF;				// this flag will cause intermittent pauses in your game!

	// perform memory check for each alloc/dealloc
	//tmpDbgFlag |= _CRTDBG_CHECK_ALWAYS_DF;				// remember this is VERY VERY SLOW!

	//_CRTDBG_LEAK_CHECK_DF is used at program initialization to force a 
	//   leak check just before program exit. This is important because
	//   some classes may dynamically allocate memory in globally constructed
	//   objects.
	tmpDbgFlag |= _CRTDBG_LEAK_CHECK_DF;					

	_CrtSetDbgFlag( tmpDbgFlag );

	HeapSetInformation( NULL, HeapEnableTerminationOnCorruption, NULL, 0 );

	// Perform application initialization
	if( !gpApp->Initialize( hInstance ))
	{
		return FALSE;
	}

	double screenRefresh = 1.0 / 60.0;
	//gpTimer->SetBaseTime();

	// Start the windows message loop
	//MSG msg;
	//memset( &msg, 0, sizeof( MSG ));

	//while( msg.message != WM_QUIT )
	double lastTime = glfwGetTime();
	while (!glfwWindowShouldClose(gpApp->GetMainWindow()))
	{
		double thisTime = glfwGetTime();
		//gpTimer->Tick();

		/*
		if( PeekMessage( &msg, 0, 0, 0, PM_REMOVE ))
		{
			// If there's a message, deal with it and send it onwards
			TranslateMessage( &msg );
			DispatchMessage( &msg );
		}
		else	// Otherwise update the game
		{
			//if( (*gpTimer).mDeltaTime > screenRefresh )
			{ */

		// Process events.
		glfwPollEvents();

		// Update the application
		gpApp->OnUpdate( thisTime, thisTime - lastTime );

		// Render the application
		gpApp->OnRender();

		lastTime = glfwGetTime();
		//gpTimer->Reset();
		//	}
		//}
	}

	// Destroy anything that needs to be killed before the deconstructor is called.
	//gpApp->Destroy();

	//... and Quit!
	return 0;
}